package com.cooper.android.comm;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.cooper.scraper.DownloadParams;
import com.cooper.scraper.HttpDownload;
import com.cooper.scraper.R;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

public class AppDownloadTask extends
		AsyncTask<String, Integer, Map<String, String>> {

	private static final String DOWNLOADS_TAG = "downloads";
	private static final String DOWNLOAD_TAG = "download";

	private String infoUrl;
	private Context context;

	private DownloadManager manager;

	public AppDownloadTask(Context context, String infoUrl) {
		super();
		this.infoUrl = infoUrl;
		this.context = context;
	}

	@Override
	protected void onPostExecute(Map<String, String> result) {
		super.onPostExecute(result);
		if (result == null) {
			Toast.makeText(context, R.string.operator_failed, Toast.LENGTH_LONG)
					.show();
		}else{
			Toast.makeText(context, R.string.added_download, Toast.LENGTH_LONG)
			.show();
		}
		//TODO download complete toast

	}

	@Override
	protected Map<String, String> doInBackground(String... names) {
		Map<String, String> result = new HashMap<String, String>(names.length);

		HttpDownload httpDownload = new HttpDownload(new DownloadParams());
		try {
			String infoPage = httpDownload.downloadPage(infoUrl, false);

			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			XmlPullParser xpp = factory.newPullParser();

			xpp.setInput(new StringReader(infoPage));
			int eventType = xpp.getEventType();
			boolean inDownloadsTag = false;
			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG) {
					if (DOWNLOADS_TAG.equals(xpp.getName())) {
						inDownloadsTag = true;
					} else if (inDownloadsTag
							&& (DOWNLOAD_TAG.equals(xpp.getName()))) {

						for (String name : names) {
							if (name.equals(xpp.getAttributeValue(null, "name"))) {
								// TODO search version for app update
								result.put(name,
										xpp.getAttributeValue(null, "uri"));
							}
						}

					}

				} else if (eventType == XmlPullParser.TEXT) {

				} else if (eventType == XmlPullParser.END_TAG) {
					if (DOWNLOADS_TAG.equals(xpp.getName())) {
						inDownloadsTag = false;
					}
				}
				eventType = xpp.next();
			}
		} catch (Exception e) {
			return null;

		}

		manager = (DownloadManager) context
				.getSystemService(Activity.DOWNLOAD_SERVICE);

		for (String name : names) {
			String appUrl = result.get(name);
			if (appUrl != null && !"".equals(appUrl.trim())) {

				DownloadManager.Request down = new DownloadManager.Request(
						Uri.parse(appUrl));

				down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
						| DownloadManager.Request.NETWORK_WIFI);

				down.setAllowedOverRoaming(false);
				down.setVisibleInDownloadsUi(true);

				// down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);

				down.setDescription(context.getResources().getString(
						R.string.app_name));

				down.setTitle(name);

				down.setDestinationInExternalPublicDir(
						Environment.DIRECTORY_DOWNLOADS, name + ".apk");

				// down.setDestinationInExternalPublicDir(
				// PrefsFragment.getTrailerScanSDCardPath(context),
				// FileUtils.stringToFileName(trailer.getTitle())
				// + "."
				// + new HttpDownload(new DownloadParams())
				// .getRemoteFileExtName(trailer
				// .getAnalyzeUri().toString()));
				manager.enqueue(down);

			}
		}

		return result;
	}

}
